<script lang="ts">
	import { goto } from '$app/navigation';
	import { page } from '$app/state';
	import type { RoadmapInfo } from '$lib/api/proto/roadmap_api';
	import { USER_ROLE } from '$lib/api/proto/user_api';
	import SimpleEditor from '$lib/components/editor/SimpleEditor.svelte';
	import UserLogin from '$lib/components/user/UserLogin.svelte';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';

	const inviteCode = page.url.searchParams.get('code') ?? '';

	let roadmapInfo = $state(null as RoadmapInfo | null);
	let showLogin = $state(false);

	async function loadRoadmapInfo() {
		const res = await callApi(
			appStore.roadmapApiClient.getByInvite({
				inviteCode: inviteCode
			}).response
		);
		roadmapInfo = res.roadmap ?? null;
	}

	loadRoadmapInfo();

	async function joinRoadmap() {
		if (userStore.userSession == null) {
			showLogin = true;
		} else {
			await realJoinRoadmap();
		}
	}

	async function realJoinRoadmap() {
		if (userStore.userSession == null || userStore.userInfo?.basicInfo == undefined) {
			return;
		}
		await callApi(
			appStore.roadmapMemberApiClient.join({
				sessionId: userStore.userSession,
				inviteCode: inviteCode
			}).response
		);
		if (userStore.userInfo.basicInfo.userRole == USER_ROLE.USER_ROLE_COACH) {
			await callApi(
				appStore.userApiClient.updateBasic({
					sessionId: userStore.userSession,
					basicInfo: {
						...userStore.userInfo.basicInfo!,
						userRole: USER_ROLE.USER_ROLE_STUDENT
					}
				}).response
			);
			if (userStore.userInfo.basicInfo != undefined) {
				userStore.userInfo.basicInfo.userRole = USER_ROLE.USER_ROLE_STUDENT;
				userStore.userInfo = {
					...userStore.userInfo
				};
			}
		}
		goto(`/app/roadmap/map?roadmapId=${roadmapInfo?.roadmapId ?? ''}`);
	}
</script>

<div class="flex items-center justify-center mt-[200px]">
	<div class="w-[400px] prose border-2 p-2 border-base-200">
		{#if roadmapInfo == null}
			<span class="loading loading-dots"></span>
			<span class="inline-block pl-2 text-2xl font-bold">加载成长路线图信息</span>
		{:else}
			<h3>成长路线图: {roadmapInfo.basicInfo?.name}</h3>
			<SimpleEditor sizeClass="" readOnly data={roadmapInfo.basicInfo?.desc ?? ''} />
			<div class="flex justify-center">
				<button class="btn btn-primary" onclick={() => joinRoadmap()}>查看</button>
			</div>
		{/if}
	</div>
</div>

<div class="absolute -left-[10000px]">
	{#if showLogin}
		<UserLogin
			onClose={() => {
				showLogin = false;
				if (userStore.userSession != null) {
					realJoinRoadmap();
				}
			}}
		/>
	{/if}
</div>
